package com.dz.lm.service.product.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dz.lm.common.dto.AgentProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.dao.product.read.ProductDao;
import com.dz.lm.dao.reminder.write.ReminderDao;
import com.dz.lm.domain.product.AgentProduct;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.product.AgentProductService;

/**
 * @author haozhiqiang
 *
 */

@Service
public class AgentProductServiceImpl extends AbstractService implements AgentProductService {

	@Resource(name="readAgentProductDao")
	private com.dz.lm.dao.product.read.AgentProductDao readAgentProductDao;
	
	@Resource(name="writeAgentProductDao")
	private com.dz.lm.dao.product.write.AgentProductDao writeAgentProductDao;
	
	@Resource(name="writeAgentDao")
	private com.dz.lm.dao.agent.write.AgentDao writeAgentDao;
	
	@Resource(name = "readCommonAreaDao")
    private com.dz.lm.dao.product.read.CommonAreaDao readCommonAreaDao;
	
	@Resource(name = "readApplyProductDao")
    private com.dz.lm.dao.business.read.ApplyProductDao readApplyProductDao;
	
    @Resource(name = "readProductDao")
    private ProductDao productDaoRead;
    
	@Resource(name = "writeReminderDao")
	private ReminderDao writeReminderDao;
    
	@Override
	public AgentProductDTO selectByPrimaryKey(Map<String, Object> param) throws ServiceException {
		AgentProduct agentProduct = new AgentProduct();
		AgentProductDTO dto = new AgentProductDTO();
		try {
			//删除提醒信息
			Map<String, Object> insertParam = new HashMap<String, Object>();
			insertParam.put("userId", param.get("userId"));
			insertParam.put("productId", param.get("productId"));
			agentProduct = readAgentProductDao.selectByPrimaryKey(param);
			if ("1".equals(agentProduct.getAgentClass())) {
				insertParam.put("type", "6");
			} else {
				//红点提示不区分一级、二级代理，将type=7 改成type=6， 2019/10/23
				insertParam.put("type", "6");
			}
			writeReminderDao.delReminder(insertParam);
			CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(agentProduct.getProvince()));
			CommonArea city = new CommonArea();
			if (agentProduct.getCity() != null) {
				city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(agentProduct.getCity()));
			}
			dto.setProductId(agentProduct.getProductId());
			dto.setProvince(agentProduct.getProvince());
			dto.setCity(agentProduct.getCity());
			dto.setArea(agentProduct.getArea());
			dto.setLongitude(agentProduct.getLongitude());
			dto.setLatitude(agentProduct.getLatitude());
			dto.setAgent(agentProduct.getAgent());
			dto.setCreateTime(agentProduct.getCreateTime());
			dto.setUpdateTime(agentProduct.getUpdateTime());
			dto.setUpDownFlag(agentProduct.getUpDownFlag());
			dto.setAgentClass(agentProduct.getAgentClass());
			dto.setAgentDescription(agentProduct.getAgentDescription());
			dto.setProduct(agentProduct.getProduct());
			dto.setTimes(DateUtil.getTimes(agentProduct.getUpdateTime()));
			dto.setAddress(province.getName() + " " + city.getName() != null ? city.getName() : "");
			dto.setBarName(agentProduct.getBarName());
			dto.setFavoriteFlag(agentProduct.getFavoriteFlag());
			dto.setApplyFlag(agentProduct.getApplyFlag());
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return dto;
	}

	@Override
	public List<AgentProductDTO> ListAgentProduct() throws ServiceException {
		return null;
	}

	@Override
	public int insert(AgentProduct agentProduct) throws ServiceException {
		try {
			return writeAgentProductDao.insert(agentProduct);
		}  catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
	}
	@Override
	public int qryAgentProductCountByAgentId(Map<String, Object> param) throws ServiceException{
		int count = 0;
		try {
			Map<String, Object> agentProductInfo = productDaoRead.qryAgentProductStateByAgentId(param);
			if (agentProductInfo != null && !agentProductInfo.isEmpty()) {
				count = Integer.valueOf(agentProductInfo.get("state").toString());
				if (count != 3) {
					count = 1;
				}
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
	}
	@Override
	public int qryProductCountByAgentId(Map<String, Object> param) throws ServiceException{
		int count = 0;
		try {
			count = productDaoRead.qryProductCountByAgentId(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
	}
	@Override
	public int delete(AgentProduct agentProduct) throws ServiceException {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	@Transactional
	public Map<String, Object> cancelProductAgentByAgentId(Map<String, Object> param) throws ServiceException {
		Map<String, Object> agentProductInfo = new HashMap<String, Object>();
		Map<String, Object> retData = new HashMap<String, Object>();
		int count = 0;
		String type = "";
		Object userId = null;
		List<Map<String, Object>> productList = new ArrayList<Map<String, Object>>(); 
		try {
			/** 2019-11-23 注释，用户无自己取消的情况 -start */
			/**
			//查询代理产品信息
			agentProductInfo = readAgentProductDao.qryAgentProductByProductId(param);
			//操作用户ID与系统用户ID相同，则用户自行操作取消
			if (String.valueOf(agentProductInfo.get("agentId")).equals(String.valueOf(param.get("activeUserId")))) {
				Map<String, Object> product = new HashMap<String, Object>();
				product.put("productId", param.get("productId"));
				productList.add(product);
			} else {//一级代理取消二级代理
				param.put("barId", agentProductInfo.get("barId"));
				param.put("agentId", agentProductInfo.get("agentId"));
				productList = readAgentProductDao.qryAgentProductListByAgentId(param);
			}
			*/
			/** 2019-11-23 注释，用户无自己取消的情况 -end */
			param.put("agentId", param.get("productId"));
			productList = readAgentProductDao.qryAgentProductListByAgentId(param);
			for (Map<String, Object> product : productList) {
				param.put("productId", product.get("productId"));
				agentProductInfo = readAgentProductDao.qryAgentProductByProductId(param);
				param.put("barId", agentProductInfo.get("barId"));
				param.put("agentClass", agentProductInfo.get("agentClass"));
				if (agentProductInfo.get("parentAgentId") == null || "".equals(agentProductInfo.get("parentAgentId").toString())) {
					param.put("parentAgentId", 0);
					type = "2";
					userId = agentProductInfo.get("createUserId");
				} else {
					param.put("parentAgentId", agentProductInfo.get("parentAgentId"));
					type = "3";
					userId = agentProductInfo.get("parentAgentId");
				}
				if (String.valueOf(param.get("userId")).equals(String.valueOf(agentProductInfo.get("agentId")))) {
					Map<String, Object> insertParam = new HashMap<String, Object>();
					insertParam.put("userId", userId);
					insertParam.put("type", type);
					insertParam.put("manageUserId", agentProductInfo.get("agentId"));
					writeReminderDao.delReminder(insertParam);
				}
				if ("0".equals(agentProductInfo.get("releaseFlag"))) {//0：待发布，1：已发布
					//物理删除代理产品信息
					writeAgentProductDao.delAgentProduct(param);
					//查询该代理人在该钱吧下是否还代理了其他产品
					count = readAgentProductDao.qryOtherAgentProductCount(param);
					if (count <= 0) {
						//该代理人在该钱吧下无其他代理产品，物理删除代理人信息
						writeAgentDao.delAgent(param);
					}
				} else {
					//查询某产品未完成申请单数
					count = readApplyProductDao.qryUnfinishedApplyCount(param);
					if (count > 0) {
						retData.put("result", "01");
						retData.put("message", "您尚有未结算的进件，无法执行此操作");//有未结清的订单无法删除该产品
						return retData;
					} else {
						//删除当前用户代理的产品数据（逻辑删除）
						writeAgentProductDao.delMyAgentProduct(param);
						//查询该代理人在该钱吧下是否还代理了其他产品
						count = readAgentProductDao.qryOtherAgentProductCount(param);
						if (count <= 0) {
							//该代理人在该钱吧下无其他代理产品，将代理人审核状态置为取消代理
							param.put("state", "3");
							writeAgentDao.cancelAgent(param);
						}
					}
				}
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
		retData.put("result", "00");
		retData.put("message", "取消成功");
		return retData;
	}
	
	public Map<String, Object> qryAgentProductInfoByProductId(Map<String, Object> param) throws ServiceException {
		try {
			return readAgentProductDao.qryAgentProductInfoByProductId(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return null;
	}
}
